define(function(require,exports,module)
{
  var $=require('jquery');
  require('bootstrap-table');
  require('bootstrap-table-zh');
  require('bootstrap-table-mobile');
  require('bootstrap-table-exp');
  var jcs = require('jcs');
  var jxKit = require('jx_kit');
  var msgbox = require('jx_msgbox') ;
  require('jx_check') ;
  require('json2') ;

  var queryParam = {} ;
  var cKey = "" ;
  $(function()
  {
    queryParam["code"] = $("#queryCode").val() ;
    cKey = $("#cKey").val() ;
    if ($.trim($("#div_label").html()) != "")
      $(".label").show() ;
    else
      $(".label").hide() ;
    
    if ($("#fieldSelect").size() > 0)
    {
      $("#queryTerm").load(cKey + "?html=-common-query-query&paras=" + $("#fieldSelect").val(),function()
      {
        jcs.initChosen();
        if ($.trim($("#div_label").html()) != "")
          findList();
        else
          findClick() ;
      }) ;
    }
    else
    {
      if ($.trim($("#div_label").html()) != "")
        findList();
      else
        findClick() ;
    }
    
    $("#fieldSelect").on("change",function()
    {
      $("#queryTerm").load(cKey + "?html=-common-query-query&paras=" + $(this).val(),function()
      {
        jcs.initChosen();
      }) ;
    });
    $(document).on("change","#s_field_mult",function()
    {
      $("#div_label").html('') ;
      findClick() ;
    });
    
    $(document).on("click","#a_term",function()
    {
      $(this).parent().remove() ;
      if ($.trim($("#div_label").html()) == "")
        $(".label").hide() ;
      findList() ;
    });  
    $(document).on("click","#a_page",function()
    {
      queryParam["page"] = $(this).attr("page") ;
      findList() ;
    });     
    $(document).on("click","#b_excel",function()
    {
      queryParam["findFlag"] = $(this).attr("para") ;
      initQueryParam() ;
      $('#GI_FORM').attr("action",cKey + "excel/" + $("#urlParams").val()) ;
      $('#GI_FORM').submit() ;
    });
    $("#b_find").on("click",function()
    {
      if (!jxCheck.check())
        return false;
      
      findClick() ;
    }) ;   
  });
  
  $(document).on("click", "#a_view", function ()
  {
    if (undefined != $(this).attr("url"))
     msgbox.show({url: encodeURI($(this).attr("url")), width:undefined == $(this).attr("width") ? document.body.clientWidth : $(this).attr("width"),height:undefined == $(this).attr("height") ? document.documentElement.clientHeight : $(this).attr("height"),title:$(this).attr("toptitle")});
  });
  $(document).on("click", "#a_prompt", function ()
  {
    var url = $(this).attr("url") ;
     msgbox.prompt({content: $(this).attr("content"),data:$(this).attr("data")},function(data)
     {
       if (data != "")
       {
         msgbox.close();
         msgbox.alert({url: encodeURI(url + "-" + data), type: "GET"}, function()
                  {
                    if (msgbox.messageType == 0)
                    {
                      msgbox.close();
                      $("#datalist").html("");
                      findList() ;
                    }
                });    
       }
     });
  });  
  $(document).on("click", "#a_del", function ()
  {
    var callBack = $(this).attr("call_back") ;
    msgbox.confirm({url: encodeURI($(this).attr("url") + "-" + $(this).attr("tip").replace(".","")), type: "GET",content:'#(jxrb.message("public.question,action.delete"))【' + $(this).attr("tip") + '】?'}, function()
                  {
                    msgbox.close();
                    if (msgbox.messageType == 0)
                    {
                      if (undefined != callBack)
                        eval(callBack) ;
                      queryParam["page"] = "1" ;
                      $("#datalist").html("");
                      findList() ;
                    }
                }, function() { });    
  });  
  $(document).on("click", "#a_confirm", function ()
  {
    var callBack = $(this).attr("call_back") ;
    msgbox.confirm({url: encodeURI($(this).attr("url") + "-" + $(this).attr("tip").replace(".","")), type: "GET",content:$(this).attr("confirm_tip") + '【' + $(this).attr("tip") + '】?'}, function()
                  {
                    msgbox.close();
                    if (msgbox.messageType == 0)
                    {
                      if (undefined != callBack)
                        eval(callBack) ;
                      queryParam["page"] = "1" ;
                      $("#datalist").html("");
                      findList() ;
                    }
                }, function() { });    
  });  
  $(document).on("change", "#select_pagelist", function ()
  {
    var pagesize = $(this).val();
    $.ajax({
      url: "#(controllerKey)saveRecordCount/" + pagesize,
      type: "POST",
      cache: false,
      success: function(data, textStatus)
      {
        queryParam["page"] = "1" ;
        queryParam["pagesize"] = pagesize ;
        $("#datalist").html("");
        findList() ;
      }
    });
  }); 
  $(document).on("click", "#a_jump_page", function ()
  {
    jumpPage() ;
  }); 
  $(document).on("keydown", "#t_page", function (e)
  {
    if (e.keyCode == 13)
      jumpPage() ;
  });   
  function jumpPage()
  {
    if (!jxKit.checkInt($("#t_page").val()))
    {
      msgbox.alert({content:"输入的页码必须是整数！"});
      return ;
    }
    if (parseInt($("#t_page").val()) > parseInt($("#t_page").attr("maxpage")))
    {
      msgbox.alert({content:"输入的页码必须小于" + $("#t_page").attr("maxpage")});
      return ;
    }    
    queryParam["page"] = $("#t_page").val() ;
    findList() ;
  }
  function initQueryParam()
  {
    queryParam["querys"] = [] ;
    $("#div_label").find("input").each(function()
    {
      queryParam["querys"].push(JSON.parse($(this).val())) ;
    });
    $("#qData").val(JSON.stringify(queryParam)) ;
  }
  
  var divfc = 0 ;
  var divfcFlag = 0 ;
  var termIndex = 0 ;

  function findClick()
  {
    divfc = 0 ;
    divfcFlag = 0 ;
    termIndex = 0 ;  
    createTerm() ;
  }

  function createTerm()
  {
    var cycflag= 0 ;
    var url = cKey ;
    var tIndex = 0 ;
    var ctFlag = 1 ;
    var divLabel = "" ;
    url +="?html=-common-query-queryLabel&" ;
    $("#div_findselect").find("[id='div_findk']").each(function(eIndex)
    {
      tIndex = eIndex ;
      if (termIndex == tIndex)
      {
        ctFlag = 0 ;
        divfc ++ ;
        var queryNum = $(this).find("#queryNum").val() ;
        if ($(this).find("#s_field_mult").length <= 0)
        {
          if (($.trim($(this).find("[qtag='termValue']").val()) == "") && (queryNum == 1))
            cycflag = 2 ;

          if (($.trim($(this).find("[qtag='termValue']").val()) == "") && ($.trim($(this).find("[qtag='termValue2']").val()) == "") && (queryNum == 2))
            cycflag = 2 ;
        }

        if (($(this).attr("tag") == "0") && ($(this).find("#chkFlag").length > 0) && (!$(this).find("#chkFlag").prop("checked")))
          cycflag = 2 ;

        if (cycflag ==0)
        {
          var termView = $(this).find("[qtag='termValue']").val() ;
          if (undefined != $(this).find("[qtag='termView']").val())
            termView = $(this).find("[qtag='termView']").val() ;

          url +="queryNum=" + queryNum ;

          if (($(this).find("#s_field_mult").length > 0) || ($.trim($(this).find("[qtag='termValue']").val()) != ""))
          {
            url += "&queryInfo.id=" ;

            if ($(this).attr("tag") == "0")
            {
              url +=$(this).find("#fieldSelectId").val() ;
              url +="&queryInfo.viewField=" ;
              url +=$(this).find("#fieldSelectView").val() ;
            }
            else
            {
              url +=$(this).find("#fieldSelect").val() ;
              url +="&queryInfo.viewField=" ;
              url +=$(this).find("#fieldSelect").find("option:selected").text() ;
            }
            url +="&queryInfo.value=" ;
            if ($(this).find("#s_field_mult").length <= 0)
            {
              url +=$(this).find("[qtag='termValue']").val() ;
              url +="&queryInfo.viewValue=" ;
              url +=termView ;      
            }
            else
            {
              url +=$(this).find("#s_field_mult").val() ;
              url +="&queryInfo.viewValue=" ;
              url +=$(this).find("#s_field_mult").find("option:selected").text() ; 
            }
            url +="&queryInfo.op=" ;
            url +=$(this).find("#fieldTerm").val() ;
            url +="&queryInfo.viewop=" ;
            url +=$(this).find("#fieldTerm").find("option:selected").text() ;    
            divLabel = "" ;
            if ($(this).attr("tag") == "0")
              divLabel = divLabel.concat($(this).find("#fieldSelectId").val(),$(this).find("#fieldTerm").val());
            else
              divLabel = divLabel.concat($(this).find("#fieldSelect").val(),$(this).find("#fieldTerm").val()) ;

            if ($("#div_label").find("[term='" + divLabel + "']").length > 0)
            {
              $("#div_label").find("[term='" + divLabel + "']").remove() ;
            }
          }

          if ((queryNum==2) && ($.trim($(this).find("[qtag='termValue2']").val()) != ""))
          {
            url += "&queryInfo2.id=" ;

            if ($(this).attr("tag") == "0")
            {
              url +=$(this).find("#fieldSelectId").val() ;
              url +="&queryInfo2.viewField=" ;
              url +=$(this).find("#fieldSelectView").val() ;
            }
            else
            {
              url +=$(this).find("#fieldSelect").val() ;
              url +="&queryInfo2.viewField=" ;
              url +=$(this).find("#fieldSelect").find("option:selected").text() ;
            }
            termView = $(this).find("[qtag='termValue2']").val() ;
            if (undefined != $(this).find("[qtag='termView2']").val())
              termView = $(this).find("[qtag='termView2']").val() ;            
            url +="&queryInfo2.value=" ;
            url +=$(this).find("[qtag='termValue2']").val() ;
            url +="&queryInfo2.viewValue=" ;
            url +=termView ;      

            url +="&queryInfo2.op=" ;
            url +=$(this).find("#fieldTerm2").val() ;
            url +="&queryInfo2.viewop=" ;
            url +=$(this).find("#fieldTerm2").find("option:selected").text() ;    

            divLabel = "" ;
            if ($(this).attr("tag") == "0")
              divLabel = divLabel.concat($(this).find("#fieldSelectId").val(),$(this).find("#fieldTerm2").val());
            else
              divLabel = divLabel.concat($(this).find("#fieldSelect").val(),$(this).find("#fieldTerm2").val()) ;

            if ($("#div_label").find("[term='" + divLabel + "']").length > 0)
            {
              $("#div_label").find("[term='" + divLabel + "']").remove() ;
            }
          }
          $.get(encodeURI(url),function(data)
          {
            $("#div_label").append(data) ;
            $(".label").show() ;
            termIndex ++ ;
            createTerm() ;
          }) ;     
        }
      }
    });
    if (cycflag !=0)
    {
      termIndex ++ ;
      createTerm() ;
    }

    if ((ctFlag == 1) && (divfc != divfcFlag) && (termIndex = tIndex + 1))
    {
      queryParam["page"] = 1 ;
      findList();
    }
  }  
  function findList()
  {
    m_xdata = [] ;
    m_datas = [] ;
    var fdata=[] ;
    var sdata = {} ;
    var qData = $("#qData").val() ;
    var dataIndex = 0 ;
    $("select").each(function()
    {
      $(this).trigger("chosen:updated") ;
    });
    initQueryParam() ;
    if (jxKit.isExitsFunction("cq_initOkEvent"))
      cq_initOkEvent($("#qData").val()) ;
    if (!((qData == $("#qData").val()) && ($.trim($("#datalist").html()) != "")))
    {
      msgbox.load({url: cKey + "list/" + $("#urlParams").val(), type: "post"}, function(data)
      {
        var pn=0 ;
        var ps=0;
        var trs = 0 ;
        if ($(data).find("[id='q_pageNumber']").length > 0)
          pn = $(data).find("[id='q_pageNumber']").val() ;
        if ($(data).find("[id='q_pageSize']").length > 0)
          ps = $(data).find("[id='q_pageSize']").val() ;
        if ($(data).find("[id='q_totalRow']").length > 0)
          trs = $(data).find("[id='q_totalRow']").val() ;        
        $("#tablePage").load(cKey + "page/" + trs +"-" + pn + "-" + ps,function()
        {
          jcs.initChosen();
        });
        $("#tabledata").bootstrapTable("removeAll");
        $("#tabledata").bootstrapTable("destroy");
        $("#tabledata").bootstrapTable('hideLoading') ;
        $("#datalist").html(data);
        
        if (undefined == chartConfig.xdata)
        {
          initBootTable() ;
          return ;
        }
        $("#datalist").find("tr").each(function(eIndex)
        {
          if (chartConfig.hasOwnProperty("igrow"))
          {
            if (chartConfig.igrow.indexOf("," +eIndex + ",") != -1)
              return true ;
          }
          for (var i=0; i<chartConfig.xdata.length; i++)
          {
            if (dataIndex >0)
              fdata = m_xdata[i] ;
            else
              fdata=[] ;
            
            if (undefined != $(this).find("[tdseq='" + chartConfig.xdata[i] +"']").html())
            {
              fdata.push($(this).find("[tdseq='" + chartConfig.xdata[i] +"']").html()) ;
            }
            m_xdata.push(fdata) ;
          }
          for (var i=0; i<chartConfig.data.length; i++)
          {
            sdata = {} ;
            if (dataIndex >0)
              fdata = m_datas[i] ;
            else
              fdata=[] ;
            
            if (undefined != $(this).find("[tdseq='" + chartConfig.data[i].value +"']").html())
            {
              sdata["value"]=$(this).find("[tdseq='" + chartConfig.data[i].value +"']").html() ;
            }
            if (undefined != $(this).find("[tdseq='" + chartConfig.data[i].name +"']").html())
            {
              sdata["name"]=$(this).find("[tdseq='" + chartConfig.data[i].name +"']").html() ;
            }
            fdata.push(sdata) ;
            m_datas.push(fdata) ;
          }
          dataIndex ++ ;
        });
        if (jxKit.isExitsFunction("loadEChart"))
          loadEChart() ;
        initBootTable() ;
      });
    }
  }
  
  function initBootTable()
  {
    $("#tabledata").bootstrapTable({
      striped: true, 
      cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
      sortable: true,                     //是否启用排序
      sortOrder: "asc",                   //排序方式
      onSort:function(name,order)
      {
        queryParam["orders"] = [] ;
        var orderInfo = {} ;
        orderInfo["id"] = name ;
        orderInfo["order"] =  order
        queryParam["orders"].push(orderInfo) ;
        findList() ;
      }		
		}) ;
		$("#tabledata").bootstrapTable('hideLoading') ;
  }
  
  window.commonQuery = findClick ;
}) ;